package com.kbbywyclient.ui.fragment.tab;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kbbywyclient.R;
import com.kbbywyclient.app.API;
import com.kbbywyclient.app.Constants;
import com.kbbywyclient.data.entity.Banner;
import com.kbbywyclient.data.entity.Event;
import com.kbbywyclient.data.entity.HotRec;
import com.kbbywyclient.data.entity.IndexData;
import com.kbbywyclient.data.model.base.BaseModel;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.IndexModule;
import com.kbbywyclient.presenter.IndexPresenter;
import com.kbbywyclient.ui.activity.LoginActivity;
import com.kbbywyclient.ui.activity.MainActivity;
import com.kbbywyclient.ui.activity.TaskActivity;
import com.kbbywyclient.ui.activity.WebViewActivity;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.adapter.HotRecAdapter;
import com.kbbywyclient.ui.contarct.IndexContract;
import com.kbbywyclient.ui.fragment.base.BaseFragment;
import com.kbbywyclient.ui.helper.ShareHelper;
import com.kbbywyclient.util.ActivitySkipUtil;
import com.kbbywyclient.util.ImageLoaderUtils;
import com.kbbywyclient.util.StringUtil;
import com.kbbywyclient.util.ToastUtil;
import com.kbbywyclient.util.ViewUtils;
import com.kbbywyclient.util.pre.PreUtils;
import com.kbbywyclient.widget.CustomPopwin;
import com.kbbywyclient.widget.ptr.PtrFrameLayout;
import com.kbbywyclient.widget.ptr.PullRefreshLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.stx.xhb.xbanner.XBanner;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrDefaultHandler;

/**
 * Created by Jiangzx on 2017/8/15 15:36.
 */

public class IndexFragment extends BaseFragment implements IndexContract.View {
    private static final int CODE_REQUEST_LOGIN_TO_TASK_ACTIVITY = 100;//登录完后去到“信用卡任务”
    private static final int CODE_REQUEST_LOGIN_RED_PACKET = 101;//登录完后处理红包相关业务
    private static final int CODE_REQUEST_LOGIN_REFRESH_DATA = 102;//登录完后需要重新刷新数据

    private static final int PADDING_DP = 10;

    @BindView(R.id.ptr_layout)
    PtrFrameLayout ptrLayout;

    @BindView(R.id.app_bar)
    AppBarLayout appBarLayout;
    @BindView(R.id.ct_layout)
    CollapsingToolbarLayout ctLayout;

    @BindView(R.id.tv_total_balance)
    TextView tvTotalBalance;//余额
    @BindView(R.id.tv_credit_card_share)
    TextView tvCreditCardShare;//办卡分享

    @BindView(R.id.ll_x_banner_container)
    LinearLayout llXBannerContainer;
    @BindView(R.id.x_banner)
    XBanner xBanner;

    @BindView(R.id.ll_title_top)
    LinearLayout llTitleTop;

    @BindView(R.id.sr_layout)
    SmartRefreshLayout srLayout;
    @BindView(R.id.recycle_view)
    RecyclerView recyclerView;

    @BindView(R.id.iv_red_packet)
    ImageView iv_red_packet;

    @Inject
    IndexPresenter presenter;
    private HotRecAdapter adapter;

    private CustomPopwin popwinRed;
    private CustomPopwin popwinExplain;

    private List<Banner.Bean> redPacketList = null;

    private boolean isLoading;//是否正在加载数据，防止同一时间请求2次数据

    private boolean hasShowRedPop;

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_index;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        redPacketList = new ArrayList<>();

        final PullRefreshLayout header = new PullRefreshLayout(getContext());
        header.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                StringUtil.dip2px(getContext(), 45)));
        ptrLayout.setHeaderView(header);
        ptrLayout.addPtrUIHandler(header);
        ptrLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(in.srain.cube.views.ptr.PtrFrameLayout frame) {
                refresh();
            }
        });
        ptrLayout.disableWhenHorizontalMove(true);

        ViewUtils.configViewHeight(xBanner, 75, 26);//xBanner宽高比为750/260
        TypedArray typedArray = getContext().obtainStyledAttributes(new int[]{android.R.attr.actionBarSize});
        int actionBarSize = typedArray.getDimensionPixelSize(0, 0);
        typedArray.recycle();
        ctLayout.setMinimumHeight(actionBarSize +
                getResources().getDimensionPixelSize(R.dimen.status_bar_height));
        appBarLayout.addOnOffsetChangedListener((appBarLayout1, verticalOffset) -> {
            if (verticalOffset == 0) {
                ptrLayout.setEnabled(true);
            } else {
                ptrLayout.setEnabled(false);
            }
            float progress =
                    (float) (((int) (Math.abs(verticalOffset) / (appBarLayout1.getTotalScrollRange() * 0.01))) * 0.01);
            llTitleTop.setAlpha(progress);
        });
        srLayout.setOnLoadmoreListener(refreshLayout -> {
            presenter.pageNo++;
            loadListData();
        });

    }

    @Override
    protected void initData() {
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE &&
                        layoutManager.findFirstCompletelyVisibleItemPosition() == 0) {
                    appBarLayout.setExpanded(true, true);
                }
            }
        });

        startRefresh();
        //加载红包数据
        if(PreUtils.isLogin(getContext())){
            presenter.getRedPacket(Constants.GLB0328);//获取红包数据
        }
    }

    private void startRefresh() {
        new Handler().postDelayed(() -> ptrLayout.autoRefresh(), 200L);
    }

    private void refresh() {
        if (!isLoading) {
            isLoading = true;
            //将appBarLayout展开
            appBarLayout.setExpanded(true, true);

            loadIndexData();//获取余额

            presenter.getBannerData(Constants.GLB0329);//获取轮播图

            //获取热门推荐数据，因为是刷新数据，先清空列表数据
            presenter.clearList();
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
            loadListData();
        }
    }

    private void loadIndexData() {
        if (PreUtils.isLogin(getContext())) {
            presenter.getIndexData(String.valueOf(PreUtils.getUser(getContext()).getSalesID()));
        } else {
            presenter.getIndexData(null);
        }
    }

    private void loadListData() {
        if (PreUtils.isLogin(getContext())) {
            presenter.getHotRecList(String.valueOf(PreUtils.getUser(getContext()).getSalesID()),
                    presenter.pageNo);
        } else {
            presenter.getHotRecList(null, presenter.pageNo);
        }
    }

    @Override
    protected void initAppComponent(AppComponent appComponent) {
        appComponent.getIndexComponent(new IndexModule(this)).inject(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event.RefreshIndex RefreshIndex) {
        switch (RefreshIndex.getType()) {
            case CODE_REQUEST_LOGIN_TO_TASK_ACTIVITY:
                //登录成功
                toTaskActivity();
                break;
            case CODE_REQUEST_LOGIN_RED_PACKET:
                presenter.getRedPacket(Constants.GLB0328);//获取红包数据
                break;
            case CODE_REQUEST_LOGIN_REFRESH_DATA:
                refresh();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAccountSignOut(Event.AccountSignOut signOut) {
        //账号退出登录，重新加载数据
        refresh();
        hasShowRedPop = false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAccountSignIn(Event.AccountSignIn signIn) {
        //账号登录，重新加载数据
        refresh();
    }

    @OnClick({R.id.tv_credit_card_share, R.id.rl_explain, R.id.iv_red_packet})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_credit_card_share:
                //办卡分享
                if (getActivity() instanceof BaseActivity) {
                    ((BaseActivity) getActivity()).setScreenAction("任务", "首页-办卡分享");
                }
                if (PreUtils.isLogin(getContext())) {
                    toTaskActivity();
                } else {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put(LoginActivity.REQUEST_LOGIN_TYPE_I, CODE_REQUEST_LOGIN_TO_TASK_ACTIVITY);
                    ActivitySkipUtil.skipAnotherActivity(this, LoginActivity.class, map);
                }
                break;
            case R.id.rl_explain:
                showExplainPopView();
                if (getActivity() instanceof BaseActivity) {
                    ((BaseActivity) getActivity()).setScreenAction("红包", "首页-现金提现介绍");
                }
                break;
            case R.id.iv_red_packet:
                //如果是手动点击红包，将hasShowRedPop清除
                hasShowRedPop=false;
                if (PreUtils.isLogin(getContext())) {
                    if (getActivity() instanceof BaseActivity) {
                        ((BaseActivity) getActivity()).setScreenAction("红包", "首页-现金红包");
                    }
                    presenter.getRedPacket(Constants.GLB0328);
                } else {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put(LoginActivity.REQUEST_LOGIN_TYPE_I, CODE_REQUEST_LOGIN_RED_PACKET);
                    ActivitySkipUtil.skipAnotherActivity(getActivity(), LoginActivity.class, map);
                }
                break;
        }
    }

    private void toTaskActivity() {
        ActivitySkipUtil.skipAnotherActivity(this, TaskActivity.class);
    }

    private void showExplainPopView() {
        View popView = LayoutInflater.from(getContext()).inflate(R.layout.pop_index_explain, null, false);
        RelativeLayout rl_cancel = (RelativeLayout) popView.findViewById(R.id.rl_cancel);

        if (popwinExplain == null) {
            popwinExplain = new CustomPopwin(getContext(), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0.6f);
        }

        popwinExplain.setContentView(popView);
        popwinExplain.showAtLocation(popView, Gravity.CENTER, 0, 0);

        rl_cancel.setOnClickListener(v -> popwinExplain.dismiss());

    }

    private void showRedPopView() {
//        PreUtils.setGuide(getContext(), false);
        View popView = LayoutInflater.from(getContext()).inflate(R.layout.pop_index_red_packet, null, false);

        ImageView iv_pic = (ImageView) popView.findViewById(R.id.iv_pic);
        RelativeLayout rl_cancel = (RelativeLayout) popView.findViewById(R.id.rl_cancel);

//        RelativeLayout rl_rec_no = (RelativeLayout) popView.findViewById(R.id.rl_rec_no);  //未领取
        RelativeLayout rl_rec = (RelativeLayout) popView.findViewById(R.id.rl_rec);//已领取

        ViewUtils.configViewHeight(iv_pic, 1, 1);

        if (popwinRed == null) {
            popwinRed = new CustomPopwin(getContext(), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0.6f);
        }

        switch (PreUtils.getUser(getContext()).getIsOpenRpacket()) {
            case 1://未领取
                if (redPacketList.size() > 0) {
                    ImageLoaderUtils.displayImage(iv_pic,
                            API.PIC_ADDRESS + redPacketList.get(0).getImage());
                }
                rl_cancel.setVisibility(View.VISIBLE);
                break;
            case 2://已领取
                if (redPacketList.size() > 1) {
                    ImageLoaderUtils.displayImage(iv_pic,
                            API.PIC_ADDRESS + redPacketList.get(1).getImage());
                }
                rl_cancel.setVisibility(View.GONE);
                break;
        }

        popwinRed.setContentView(popView);
        if (isVisible() && !hasShowRedPop) {
            hasShowRedPop = true;
            popwinRed.showAtLocation(popView, Gravity.CENTER, 0, 0);
        }

        rl_rec.setOnClickListener(v -> {
            switch (PreUtils.getUser(getContext()).getIsOpenRpacket()) {
                case 1:
                    presenter.updateSaleBalance(getUser().getSalesID() + "");
                    if (getActivity() instanceof BaseActivity) {
                        ((BaseActivity) getActivity()).setScreenAction("红包", "首页-立即领取红包");
                    }
                    break;
                case 2:
                    if (PreUtils.isLogin(getContext())) {
                        if (getActivity() instanceof BaseActivity) {
                            ((BaseActivity) getActivity()).setScreenAction("红包", "首页-红包弹窗-开始做任务");
                        }
                        ActivitySkipUtil.skipAnotherActivity(this, TaskActivity.class);
                    } else {
                        ActivitySkipUtil.skipAnotherActivity(this, LoginActivity.class);
                    }
                    break;
            }
            popwinRed.dismiss();
        });
        rl_cancel.setOnClickListener(v -> {
            if (getActivity() instanceof BaseActivity) {
                ((BaseActivity) getActivity()).setScreenAction("红包", "首页-红包弹窗-关闭");
            }
            popwinRed.dismiss();
        });
    }

    @Override
    public void showLoadingDialog(String s) {
        showProgress(s);
    }

    @Override
    public void closeLoadingDialog() {
        dismissProgress();
    }

    @Override
    public void finishRefresh() {
        if (ptrLayout.isRefreshing()) {
            new Handler().postDelayed(() -> ptrLayout.refreshComplete(), 200L);
        }
    }

    @Override
    public void onIndexDataSuccess(IndexData data) {
        setBalance(data.getBalance());
        List<IndexData.Tab> tabs = data.getTabs();
        if (tabs != null && tabs.size() >= 1) {
            setTabFirst(tabs.get(0));
        }
        isLoading = false;
    }

    @Override
    public void onIndexDataFailure() {
        tvTotalBalance.setText("0.00");
        isLoading = false;
    }

    @Override
    public void onBannerSuccess(final List<Banner.Bean> list) {
        int padding = DensityUtil.dp2px(PADDING_DP);
        llXBannerContainer.setPadding(0, padding, 0, padding);
        xBanner.setVisibility(View.VISIBLE);
        xBanner.setData(list, null);
        xBanner.setmAdapter((banner, model, view, position) ->
                ImageLoaderUtils.displayImage((ImageView) view,
                        API.PIC_ADDRESS + ((Banner.Bean) model).getImage()));
        xBanner.setOnItemClickListener((banner, position) -> {
            Banner.Bean bean = list.get(position);
            if (getActivity() instanceof BaseActivity) {
                ((BaseActivity) getActivity()).setScreenAction("广告", "首页-banner点击", bean.getUrl());
            }
            if (!TextUtils.isEmpty(bean.getUrl())) {
                HashMap<String, Object> params = new HashMap<>();
                params.put(WebViewActivity.KEY_URL_S,
                        bean.getUrl());
                params.put(WebViewActivity.KEY_TITLE_S,
                        bean.getTopical());
                ActivitySkipUtil.skipAnotherActivity(IndexFragment.this,
                        WebViewActivity.class, params);
            }
        });
        xBanner.startAutoPlay();
    }

    @Override
    public void hideBanner() {
        llXBannerContainer.setPadding(0, DensityUtil.dp2px(PADDING_DP), 0, 0);
        xBanner.setVisibility(View.GONE);
    }

    @Override
    public void onRedPacketSuccess(List<Banner.Bean> list) {
        redPacketList.clear();
        redPacketList.addAll(list);
        if (list.size() > 0) {
//                    if (PreUtils.isGuide(getContext())) {
            showRedPopView();
//                    }
        }
    }

    @Override
    public void setListUi(List<HotRec> data, boolean canLoadMore) {
        if (adapter == null) {
            adapter = new HotRecAdapter(data);
            adapter.setOnItemClickedListener((hotRec, action) -> {
                if (PreUtils.isLogin(getContext())) {
                    switch (action) {
                        case HotRecAdapter.OnItemClickedListener.ACTION_GO_DETAILED:
                            if (getActivity() instanceof BaseActivity) {
                                ((BaseActivity) getActivity()).setScreenAction("推荐",
                                        "首页-热门推荐-列表项点击",
                                        hotRec.getName());
                            }
                            if (TextUtils.isEmpty(hotRec.getJub_url())) {
                                //进详情页面
                                int salesId = PreUtils.getUser(getContext()).getSalesID();
                                String detailedUrl = API.CARD_DETAILE_URL +
                                        "?cardID=" + hotRec.getID() +
                                        "&saleID=" + salesId +
                                        "&Code=" + Constants.DCP021701;
                                HashMap<String, Object> params = new HashMap<>();
                                params.put(WebViewActivity.KEY_URL_S, detailedUrl);
                                params.put(WebViewActivity.KEY_TITLE_S,
                                        getContext().getString(R.string.text_card_share_details));
                                params.put(WebViewActivity.KEY_SCREEN_NAME_S,
                                        "信用卡分享详情");
                                params.put(WebViewActivity.KEY_CARD_NAME,
                                        hotRec.getName());
                                ActivitySkipUtil.skipAnotherActivity(IndexFragment.this,
                                        WebViewActivity.class, params);
                            }
                            break;
                        case HotRecAdapter.OnItemClickedListener.ACTION_SHARE:
                            Context context = getContext();
                            if (TextUtils.isEmpty(hotRec.getJub_url())) {
                                //分享
                                final ShareHelper.ShareBody shareBody = new ShareHelper.ShareBody();
                                if (PreUtils.isAuthenticated(context)) {
                                    shareBody.title = "您的好友" +
                                            PreUtils.getTrueName(context) +
                                            "邀请您申请" + hotRec.getName() +
                                            ",优惠好礼享不停";
                                } else {
                                    shareBody.title = "您的好友邀请您申请" +
                                            hotRec.getName() +
                                            ",优惠好礼享不停";
                                }
                                shareBody.statisticsTitle = hotRec.getName();
                                shareBody.url = API.WEB_ADDRESS + hotRec.getShareURL();
                                Activity activity = getActivity();
                                if (activity != null && activity instanceof MainActivity) {
                                    ((MainActivity) activity).share(shareBody);
                                }
                            } else {
                                //进第三方网页
                                HashMap<String, Object> webParams = new HashMap<>();
                                webParams.put(WebViewActivity.KEY_TITLE_S,
                                        context.getString(R.string.text_bank_recommend_page));
                                webParams.put(WebViewActivity.KEY_URL_S, hotRec.getJub_url());
                                ActivitySkipUtil.skipAnotherActivity(IndexFragment.this,
                                        WebViewActivity.class, webParams);
                            }
                            break;
                    }
                } else {
                    //去登录
                    HashMap<String, Object> map = new HashMap<>();
                    map.put(LoginActivity.REQUEST_LOGIN_TYPE_I, CODE_REQUEST_LOGIN_REFRESH_DATA);
                    ActivitySkipUtil.skipAnotherActivity(IndexFragment.this, LoginActivity.class, map);
                }
            });
        }
        if (recyclerView.getAdapter() == null) {
            recyclerView.setAdapter(adapter);
        }
        adapter.notifyDataSetChanged();
        srLayout.finishLoadmore();
        if (canLoadMore) {
            srLayout.setLoadmoreFinished(false);
        } else {
            srLayout.setLoadmoreFinished(true);
        }
    }

    @Override
    public void loadListEmpty() {
        srLayout.finishLoadmore();
    }

    @Override
    public void loadSucUpdate(BaseModel baseModel) {
        if (isVisible()) {
            ToastUtil.showShort(baseModel.getMsg());
            PreUtils.setisOpenPacket(getContext(), baseModel.getIsOpenRpacket());
            popwinRed.dismiss();
            showRedPopView();
            if (baseModel.getIsOpenRpacket() == 2) {
                iv_red_packet.setVisibility(View.GONE);
                PreUtils.getUser(getContext()).setIsOpenRpacket(2);
                loadIndexData();
            } else {
                iv_red_packet.setVisibility(View.VISIBLE);
            }
        }
    }

    private void setBalance(String balance) {
        if (TextUtils.isEmpty(balance)) {
            tvTotalBalance.setText("0.00");
        } else {
            tvTotalBalance.setText(balance);
        }
    }

    private void setTabFirst(IndexData.Tab tab) {
        ViewUtils.setText(tvCreditCardShare, tab.getName());
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (isVisible()) {
            if (xBanner!=null&&xBanner.getVisibility() == View.VISIBLE) {
                xBanner.startAutoPlay();
            }
            if (PreUtils.isLogin(getContext())) {
                if (PreUtils.getUser(getContext()).getIsOpenRpacket() == 2) {
                    //已领取红包
                    iv_red_packet.setVisibility(View.GONE);
                } else {
                    //未领取红包
                    iv_red_packet.setVisibility(View.VISIBLE);
                }
            } else {
                iv_red_packet.setVisibility(View.VISIBLE);
            }
        } else {
            if (xBanner!=null&&xBanner.getVisibility() == View.VISIBLE) {
                xBanner.startAutoPlay();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
